package com.cop4331.social;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

/**
 * 
 * @author Matt Szoke
 * @LastUpdated: 4/12/2012 by Matt Szoke
 * 
 * User main Dashboard
 * 
 */
public class DashBoardActivity extends Activity {

	Button viewprofile;
	Button search;
	Button logout;
	Button notifications;
	Button messages;
	ImageButton about;
	ImageButton home;
	ImageButton message;

	// -----------------------------------------------
	// ONCREATE
	// -----------------------------------------------
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		// Assign XML
		setContentView(R.layout.dashboard);
		
		// Buttons
		viewprofile = (Button) findViewById(R.id.profilebutton);
		search = (Button) findViewById(R.id.tutorbutton);
		logout = (Button) findViewById(R.id.b_logout);
		messages = (Button) findViewById(R.id.messagebutton);
		notifications = (Button) findViewById(R.id.notifybutton);
		
		// Image buttons
		about = (ImageButton) findViewById(R.id.b_about);
		home = (ImageButton) findViewById(R.id.b_home);
		message = (ImageButton) findViewById(R.id.b_message);

		// Get current user info from database
		DatabaseHandler db = new DatabaseHandler(getApplicationContext());
		HashMap<String, String> user = db.getUserDetails();
		String un = user.get("name");
		final UserFunctions uf = new UserFunctions();
		
		// Check if user exists
		JSONObject json = uf.userExists(un);
		
		// Check the list of session dates
		// If session date has passed, we need to review the user
		this.dateCheck(un);
		
		// Check for new messages
		JSONObject j_mess = uf.retreiveMessages(un, "new");

		try {
			if (Integer.parseInt(j_mess.getString("size")) > 0) {
				message.setVisibility(View.VISIBLE);
			} else
				message.setVisibility(View.GONE);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		// Return to login screen
		logout.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				uf.logoutUser(getApplicationContext());

				Intent sa = new Intent(getApplicationContext(),
						LoginActivity.class);
				startActivity(sa);
				finish();

			}
		});
		
		// Goto View Profile
		viewprofile.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent vp = new Intent(getApplicationContext(),
						ViewProfileActivity.class);
				startActivity(vp);
				finish();

			}
		});
		
		// Goto Inbox
		messages.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent n = new Intent(getApplicationContext(),
						MessageNotifications.class);
				startActivity(n);
				finish();

			}
		});
		
		// Goto Session Notifications
		notifications.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent n = new Intent(getApplicationContext(),
						TutorNotifications.class);
				startActivity(n);
				finish();

			}
		});
		
		// Look for tutor
		search.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent sa = new Intent(getApplicationContext(),
						NeedTutorActivity.class);
				startActivity(sa);
				finish();

			}
		});
	
		// Show app info
		about.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Dialog dialog = new Dialog(DashBoardActivity.this);

				dialog.setContentView(R.layout.help_dialog);
				dialog.setTitle("CramSessions v 1.0 2012");
				dialog.setCancelable(true);

				// Create and show a dialog to help the user with this specific
				// field
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("CramSessions was created by:\n\n-Matt Szoke\n-Daniel Moody\n-Jeovanny Alvarez\n-Kia Manoochehri\n-Rj Anderson\n-Doug Wagner");
				text.setGravity(Gravity.LEFT);
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();
			}
		});
		
		// If new message exists, show inbox button
		message.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent sa = new Intent(getApplicationContext(),
						MessageNotifications.class);
				startActivity(sa);
				finish();

			}
		});
		
		// Return home
		home.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				Intent sa = new Intent(getApplicationContext(),
						DashBoardActivity.class);
				startActivity(sa);
				finish();

			}
		});
	}
	
	// -----------------------------------------------
	// DATECHECK
	// -----------------------------------------------
	public void dateCheck(String un) {
		
		// Get current date info
		final Calendar c = Calendar.getInstance();
		int mYear = c.get(Calendar.YEAR);
		int mMonth = c.get(Calendar.MONTH);
		int mDay = c.get(Calendar.DAY_OF_MONTH);
		
		String currDate;
		
		mMonth = mMonth + 1;

		String monthHolder = Integer.toString((mMonth));
		String dayHolder = Integer.toString(mDay);

		if (monthHolder.length() == 1)
			monthHolder = "0" + monthHolder;

		if (dayHolder.length() == 1)
			dayHolder = "0" + dayHolder;
		
		// Format date to string for comparable
		currDate = monthHolder + "/" + dayHolder + "/" + mYear;
		
		// Retreive user session notifications
		final UserFunctions uf = new UserFunctions();
		JSONObject tutorCheck = uf.retreiveTutorNotifications(un, "5");

		try {
			int size = Integer.parseInt(tutorCheck.getString("size"));

			// Loop the size of the list
			for (int i = 0; i < size; i++) {
				try {

					Map<String, Object> map = new HashMap<String, Object>();

					// Each object is stored in relation to an String integer,
					// i.e "1", "2", "3", ...
					final JSONObject json_not = tutorCheck
							.getJSONObject("" + i);
					
					// If the current date is past the session date, do this
					if (currDate.compareTo(json_not.getString("date")) > 0) {
						
						// If it is not a active session, just remove it
						// All pending requests are deleted
						if (json_not.getString("type").compareTo("2") != 0) {
							uf.deleteSession(json_not.getString("id"));
						} 
						else {
							
							// Create rating dialog for user
							final Dialog dialog = new Dialog(
									DashBoardActivity.this);
							dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
							dialog.setContentView(R.layout.rating);
							dialog.setCancelable(false);
							
							// TextView
							TextView prompt = (TextView) dialog
									.findViewById(R.id.tv_prompt);
							TextView prompt2 = (TextView) dialog
									.findViewById(R.id.tv_prompt2);
							
							// RatingBar
							final RatingBar rating = (RatingBar) dialog
									.findViewById(R.id.rating);
							
							// Button
							Button ok = (Button) dialog.findViewById(R.id.ok);
							
							// Holds the user to be rated
							final String ratedUser;
							
							// We are rating a tutoree
							if (un.compareTo(json_not.getString("tutor")) == 0) {
								prompt.setText("Rate your session tutoring "
										+ json_not.getString("tutoree") + ".");
								prompt2.setText("Be sure to rate on work ethic, not ability!");
								ratedUser = json_not.getString("tutoree");
							} 
							
							// We are rating a tutor
							else {
								prompt.setText("Rate your session learning from "
										+ json_not.getString("tutor") + ".");
								prompt2.setText("Be sure to rate on helpfulness!");
								ratedUser = json_not.getString("tutor");
							}

							dialog.setCanceledOnTouchOutside(false);
							dialog.show();
							
							// Gives function to Ok button
							ok.setOnClickListener(new View.OnClickListener() {

								public void onClick(View v) {

									JSONObject json = uf.userExists(ratedUser);

									try {

										JSONObject juser = json
												.getJSONObject("user");

										double rate = rating.getRating();
										
										double avg = Double.parseDouble(juser
												.getString("rating"));
										int count = Integer.parseInt(juser
												.getString("numRatings")) + 1;
										
										// Compute new rating
										avg = (((avg * (count - 1)) + rate))
												/ count;
										
										// Update database
										uf.updateRating(ratedUser, avg + "",
												count + "");

										dialog.dismiss();
										
										// Delete this session after rating
										uf.deleteSession(json_not
												.getString("id"));

									} catch (JSONException e) {
										e.printStackTrace();
									}

								}
							});
						}
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (NumberFormatException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
}
